<template>
  <el-scrollbar height="100%">
    <avue-crud :data="data"
               :table-loading="tableLoading"
               :option="menuTableOption"
               v-model:search="search"
               @row-del="remove"
               @row-update="update"
               @select="select"
               @search-change="searchChange"
               @refresh-change="refreshChange"
               @search-reset="resetChange">
      <template #menu-left="{ size }">
        <el-space>
          <menu-add-form :size="size" @reflash-page="getMenuTree"/>
          <menu-batch-delete :size="size" :menu-ids="selected"
                             @delete-change="finishChange"/>
        </el-space>
      </template>
      <template #menu="{ row, size }">
        <menu-children-add-form :size="size" :parent-id="row.id" @reflash-page="getMenuTree"/>
      </template>
    </avue-crud>
  </el-scrollbar>
</template>

<script setup>
import {ref, onMounted} from "vue";
import {menuTableOption} from "@/views/system/menu/js/menuOptions.js";
import menuAddForm from "@/views/system/menu/components/menuAddForm.vue";
import {menuDelete, menuModify, menuTree} from "@/views/system/menu/js/menuRequest.js";
import {ElMessage, ElMessageBox} from "element-plus";
import menuBatchDelete from "@/views/system/menu/components/menuBatchDelete.vue";
import MenuChildrenAddForm from "@/views/system/menu/components/MenuChildrenAddForm.vue";
import Func from "@/utils/Utils.js";

onMounted(() => {
  getMenuTree()
})

const tableLoading = ref(true)
const selected = ref('')
const data = ref([]);

const search = ref({})

const select = (selection) => {
  if (selection.length === 0) {
    selected.value = ''
    return
  }
  let tempStr = ''
  selection.forEach(item => {
    tempStr = tempStr + item.id + ','
  })
  selected.value = tempStr.substring(0, tempStr.length - 1)
}

const remove = (form, index, done) => {
  ElMessageBox.confirm('是否删除, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    menuDelete(form.id).then(res => {
      if (res.success) {
        ElMessage.success('删除成功!');
        getMenuTree()
      }
    }).finally(() => {
      done();
    })
  }).catch(() => {
  });
}

const getMenuTree = () => {
  menuTree().then(res => {
    if (res.success) {
      data.value = res.data
    }
  }).finally(() => {
    tableLoading.value = false
  })
}

const finishChange = () => {
  getMenuTree()
}

const searchChange = (params, done) => {
  getMenuTree()
  Func.queryFinish()
  done()
}

const resetChange = () => {
  search.value = {}
  getMenuTree()
}

const refreshChange = () => {
  getMenuTree()
  Func.refreshFinish()
}

const update = (row, index, done, loading) => {
  menuModify(row).then(res => {
    if (res.success) {
      ElMessage.success("修改成功")
    }
  }).finally(() => {
    done()
    loading()
    getMenuTree()
  })
}

</script>
